package com.google.code.stalkernet.chat.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.util.Arrays;
import java.util.concurrent.Executor;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.TableRowSorter;

import com.google.code.stalkernet.chat.ui.action.SendMessageAction;
import com.google.code.stalkernet.chat.ui.model.ChatTableModel;
import com.google.code.stalkernet.database.Database;

/**
 * Stalker.Net Char main frame.
 *
 * @author Mikhail Vladimirov
 */
public class MainFrame extends JFrame
{
    private final ChatTableModel chatTableModel;
    private final TableRowSorter <ChatTableModel> chatTableRowSorter;
    private final JTable chatTable;
    private final JScrollPane chatScrollPane;
    private final JTextField messageTextField;
    private final JButton sendMessageButton;
    private final JPanel messagePanel;
    private final JPanel mainPanel;

    /**
     * Create new main frame.
     *
     * @param database {@link Database} to use
     * @param executor {@link Exception} to use for database-related operations
     * @param author author for new added messages
     */
    public MainFrame (Database database, Executor executor, String author)
    {
        super ("Stalker.Net Chat");

        chatTableModel = new ChatTableModel (database, executor);

        chatTableRowSorter = new TableRowSorter<> (chatTableModel);
        chatTableRowSorter.setSortKeys (
            Arrays.asList (new RowSorter.SortKey (0, SortOrder.ASCENDING)));

        chatTable = new JTable (chatTableModel);
        chatTable.setRowSorter (chatTableRowSorter);

        chatScrollPane = new JScrollPane (
            chatTable,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        messageTextField = new JTextField ();

        sendMessageButton = new JButton (
            new SendMessageAction (
                messageTextField.getDocument (), database, executor, author));

        messagePanel = new JPanel (new BorderLayout (8, 8));
        messagePanel.add (messageTextField, BorderLayout.CENTER);
        messagePanel.add (sendMessageButton, BorderLayout.EAST);

        mainPanel = new JPanel (new BorderLayout (8, 8));
        mainPanel.setBorder (BorderFactory.createEmptyBorder (8, 8, 8, 8));
        mainPanel.add (chatScrollPane, BorderLayout.CENTER);
        mainPanel.add (messagePanel, BorderLayout.SOUTH);

        Container contentPane = getContentPane ();
        contentPane.setLayout (new BorderLayout ());
        contentPane.add (mainPanel, BorderLayout.CENTER);

        getRootPane ().setDefaultButton (sendMessageButton);
    }
}
